using NaughtyAttributes;
using UnityEngine;
using ZSW.Framework;
using ZSW.Framework.Utils;

namespace ZSW.Framework.UIElement
{
    [RequireComponent(typeof(CanvasGroup))]
    public class ZSWF_BaseUIElement : ZSWF_InitMonoBehaviour
    {
        public bool IsVisible { get => m_isVisible; protected set => m_isVisible = value; }
        [SerializeField, ShowIf("m_override")] protected CanvasGroup m_canvasGroup;
        [SerializeField, ShowIf("m_override")] private float m_fadeInTime = 0.5f;
        [SerializeField, ShowIf("m_override")] private float m_fadeOutTime = 0.5f;
        [SerializeField, ShowIf("m_override"), ReadOnly] private bool m_isVisible;
        private Coroutine m_fadeIn;
        private Coroutine m_fadeOut;
        protected readonly int ScreenZoom = Screen.width / 1920;

        public override void Init()
        {
            m_canvasGroup = this.GetComponent<CanvasGroup>();
            base.Init();
        }

        public virtual void Show()
        {
            IsVisible = true;
            gameObject.SetActive(true);
            stopAllCoroutines();
            // m_canvasGroup.alpha = 0f;
            if (gameObject.activeInHierarchy)
            {
                m_fadeIn = StartCoroutine(ZSWFUtil_UI.fadeIn(m_canvasGroup, m_fadeInTime, () =>
                {
                    m_fadeIn = null;
                }));
            }
        }

        public virtual void Hide()
        {
            IsVisible = false;
            stopAllCoroutines();
            //m_canvasGroup.alpha = 1f;
            if (gameObject.activeInHierarchy)
            {
                m_fadeOut = StartCoroutine(ZSWFUtil_UI.fadeOut(m_canvasGroup, m_fadeOutTime, () =>
                {
                    m_fadeOut = null;
                    gameObject.SetActive(false);
                }));
            }
            else
            {
                m_fadeOut = null;
                gameObject.SetActive(false);
            }
        }

        public void SwitchState(bool isShow)
        {
            bool isActive = gameObject.activeSelf;
            float currentAlpha = m_canvasGroup.alpha;

            if (isShow)
            {
                // 当前未激活 或 当前透明度小于1时
                if (!isActive || currentAlpha < 1)
                {
                    Show();
                }
            }
            else if (isActive && (currentAlpha > 0 || currentAlpha < 1))
            {
                Hide();
            }
        }

        private void stopAllCoroutines()
        {
            if (m_fadeIn != null)
            {
                StopCoroutine(m_fadeIn);
            }
            if (m_fadeOut != null)
            {
                StopCoroutine(m_fadeOut);
            }
        }

    }
}